<template>
  <div class="common-layout">
    <el-container>
      <div class="side">
        <el-menu default-active="1-4-1" class="el-menu-vertical-demo" @open="handleOpen" @close="handleClose"
          :collapse="isCollapse">
          <div class="sidebar-logo-container" @click="handleLogout">
            <!-- <router-link class="sidebar-logo-link"> -->
            <img v-if="logo" :src="logo" class="sidebar-logo" />
            <h1 class="sidebar-title">{{ title }}</h1>
            <!-- </router-link> -->

          </div>

          <el-menu-item index="1">
            <router-link class="nav-link" to="/userIndex/personal">
              <el-icon style="color:rgb(191, 203, 217);">
                <Avatar />
              </el-icon>
              <!-- <i class="el-icon-menu"></i> -->
              <span>个人中心</span>
            </router-link>
          </el-menu-item>

          <el-menu-item index="2">
            <router-link to="/userIndex/totalWorkUser">
              <el-icon style="color:rgb(191, 203, 217);">
                <InfoFilled />
              </el-icon>
              <span>总工作量</span>
            </router-link>
          </el-menu-item>

          <el-menu-item index="3">
            <router-link to="/userIndex/researchProjectUser">
              <el-icon style="color:rgb(191, 203, 217);">
                <GoodsFilled />
              </el-icon>
              <span>科研项目工作量</span></router-link>
          </el-menu-item>

          <el-sub-menu index="4">
            <template #title>
              <el-icon style="color:rgb(191, 203, 217);">
                <LocationFilled />
              </el-icon>
              <span>我的科研库</span>
            </template>
            <!-- 子菜单项 -->
            <el-menu-item index="4-1">
              <router-link class="nav-link" to="/userIndex/academicWorksUser">
                <span>学术著作</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/decisionConsultUser">
                <span>决策咨询类</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/creativeAchieveUser">
                <span>创作成果类</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/intellectualPropertyUser">
                <span>知识产权类</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/achieveTransferUser">
                <span>成果转化类</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/natureResearchAwardUser">
                <span>科研奖项（自然科学）</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/humanResearchAwardUser">
                <span>科研奖项（人文社科）</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/networkCultureUser">
                <span>网络文化成果</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/academicPapersUser">
                <span>学术论文</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/scientificActivityUser">
                <span>科技活动</span>
              </router-link>
            </el-menu-item>
            <el-menu-item index="4-2">
              <router-link class="nav-link" to="/userIndex/researchPlatformUser">
                <span>重要平台</span>
              </router-link>
            </el-menu-item>

          </el-sub-menu>
          <!--  -->
        </el-menu>
      </div>
      <el-container>

       <!-- 顶部导航栏 -->
       <el-header class="navbar">
          <el-button type="text" class="toggle-button" @click="toggleCollapse">
            <el-icon>
              <Fold />
            </el-icon>
          </el-button>
          <Breadcrumb :history="history" />
 <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + upload.updateSupport"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <!-- <div class="el-upload__tip">
                     <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
                  </div> -->
                  <span>仅允许导入xls、xlsx格式文件。</span>
               </div>
            </template>
         </el-upload>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitFileForm">确 定</el-button>
               <el-button @click="upload.open = false">取 消</el-button>
            </div>
         </template>
      </el-dialog>
          <!-- 新增的下拉菜单 -->
          <div class="user-dropdown">
            <el-button
                     type="info"
                     plain
                     icon="Upload"
                     @click="handleImport"
                     v-hasPermi="['user:import']"
                  >导入</el-button>
               <!-- <el-button
                     type=""
                     plain
                     icon="Upload"
                     @click="openUploadDialog"
                    
                     style="border: none; color: black;background-color: none;"
                  >导入总表</el-button>-->
 <!--引入上传对话框组件 -->
<!-- <Imports
      ref="uploadDialogRef"
      :title="'用户导入'"
      :url="uploadUrl"
      @success="handleUploadSuccess"
      @close="handleUploadClose"
    />   -->
                  <!-- 竖线 -->
<span style="color: black; margin: 0 10px;">|</span>

            <el-dropdown>
              <span class="el-dropdown-link">
                <!-- 显示用户名 -->
                <p style="color: black;">您好，{{ user.username }}</p>
                <!--                <img src="@/assets/images/outTop.jpg" alt="User" style="width: 36px;height: 36px;border-radius: 50%;">-->
                <el-icon class="el-icon--right">
                  <ArrowDown />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </div>
        </el-header>

        <!-- 标签页 -->
        <el-tabs v-model="editableTabsValue" type="card" @tab-remove="removeTab" @tab-click="handleTabClick">
          <el-tab-pane v-for="item in history" :key="item.path" :label="item.title" :name="item.path"
            :closable="item.path !== '/'" :class="{ 'is-active': item.path === editableTabsValue }">
          </el-tab-pane>
        </el-tabs>

        <el-main>
          <router-view></router-view>
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import logo from '@/assets/logo/logo.png'
import { ref, watch,reactive,onMounted } from 'vue';
import { Fold, ArrowDown } from '@element-plus/icons-vue';
import { logout } from '@/api/auth';
import { cartListUser } from '@/api/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

const isCollapse = ref(false);
const router = useRouter();
const route = useRoute();

function toggleCollapse() {
  isCollapse.value = !isCollapse.value;
}

const title = ref('科研服务管理平台');
// 定义用户信息对象
const user = reactive({
  username: '未知用户'
});
const editableTabsValue = ref('/');
const history = ref([{ title: '首页', path: '/adminIndex/user' }]);

/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入";
  upload.open = true;
};

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 上传的地址
  url: "http://localhost:8080/sumImportData/excel",
  // headers: {
  //   withCredentials: true
  // },
  // url: import.meta.env.VITE_APP_BASE_API + "/user/importData"
});
// 定义上传地址
// const uploadUrl = ref("http://localhost:8080/sumImportData/excel");

// 监听路由变化并更新历史
watch(route, (to) => {
  // 如果是首次加载或路由改变，则添加新标签页
  if (!history.value.find(item => item.path === to.path)) {
    addTab(to.path);
  } else {
    // 如果已经存在则直接激活
    editableTabsValue.value = to.path;
  }
}, { immediate: true });

// 添加标签页的方法
function addTab(path) {
  const tab = { title: route.matched.find(record => record.path === path)?.meta?.title || '未知', path };
  if (!history.value.find(item => item.path === tab.path)) {
    history.value.push(tab);
  }
  editableTabsValue.value = tab.path;
  router.push(tab.path);
}

// 移除标签页的方法
function removeTab(targetName) {
  let tabs = history.value;
  let activeName = editableTabsValue.value;
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.path === targetName) {
        let nextTab = tabs[index + 1] || tabs[index - 1];
        if (nextTab) {
          activeName = nextTab.path;
        }
      }
    });
  }

  editableTabsValue.value = activeName;
  history.value = tabs.filter(tab => tab.path !== targetName);
  router.push(activeName);
}
// 切换标签页的方法
function handleTabClick(tab) {
  router.push(tab.props.name);
}

const fetchCurrentUser = async () => {
  try {
    const response = await cartListUser(); // 调用正确的 API 方法
    const data = response;
    console.log("1111=",data);

    // 确保只使用需要的字段
    user.username = data.username || '未知用户';
  } catch (error) {
    // 避免打印完整错误对象，仅打印错误消息
    console.error('Failed to fetch user info: 未知错误');
  }
};



const handleLogout = async () => {
  try {
    await logout();
    ElMessage.success('注销成功');
    router.push('/login'); // 跳转到登录页面
  } catch (error) {
    console.error("注销失败:", error);
    ElMessage.error('注销失败，请稍后重试');
  }
};

onMounted(() => {
  fetchCurrentUser();
});
</script>

<style lang="scss" scoped>
//  @import '@/assets/css/app.css';
@import '@/assets/css/chunkcss.css';

.el-menu-vertical-demo {
  height: 1000px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.toggle-button {
  position: absolute;
  top: 9px;
  left: 4px;
  color: #1c2127;
  width: 36px;
  /* 设置宽度 */
  height: 36px;
  /* 设置高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  /* 移除默认填充 */
}

/* 确保图标也适应按钮的新尺寸 */
.toggle-button .el-icon {
  font-size: 18px;
  /* 根据需要调整 */
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.sidebarLogoFade-enter-active {
  transition: opacity 1.5s;
}

.sidebarLogoFade-enter,
.sidebarLogoFade-leave-to {
  opacity: 0;
}


.sidebar-logo-container {
  position: relative;
  width: 100%;
  height: 50px;
  line-height: 50px;
  background-color: rgb(48, 65, 86) !important;
  // background: #2b2f3a;
  text-align: center;
  overflow: hidden;



  .sidebar-title {
    display: inline-block;
    margin: 0;
    color: #fff !important;
    font-weight: 600;
    line-height: 50px;
    font-size: 14px;
    font-family: Avenir, Helvetica Neue, Arial, Helvetica, sans-serif;
    vertical-align: middle;
  }

  .sidebar-logo {
    width: 32px;
    height: 32px;
    vertical-align: middle;
    margin-right: 12px;
  }


  .collapse {
    .sidebar-logo {
      margin-right: 0px;
    }
  }
}

.el-scrollbar {
  background-color: rgb(48, 65, 86) !important;
}

.el-menu {
  background-color: rgb(48, 65, 86);
}

.el-menu-item {
  color: #fff;
}

.sidebar-logo-container .sidebar-logo-link .sidebar-logo {
  margin-right: 0px;
}

.navbar {
  height: 50px;
  overflow: visible;
  /* 确保下拉菜单可以超出此元素 */
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-dropdown {
  margin-right: 16px;
  position: relative;
  /* 确保相对定位 */
  z-index: 1000;
  /* 提高z-index以确保下拉菜单可以在最上层 */
}

/* 增加下拉菜单的 z-index 并确保其不会受到任何父元素的影响 */
:deep(.el-dropdown-menu) {
  z-index: 1001 !important;
  /* 确保下拉菜单总是在最顶层 */
  position: absolute !important;
  /* 强制绝对定位 */
}

/* 防止其他全局样式影响 */
:deep(.el-popper) {
  z-index: 1001 !important;
  /* 确保 popper 容器也在最顶层 */
}

.el-dropdown-link img {
  vertical-align: middle;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-breadcrumb {
  margin-left: 30px;
  margin-top: 5px;
}

.el-main {
  margin-top: -36px;
}

/* 标签页的基本样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  display: inline-block;
  position: relative;
  cursor: pointer;
  height: 26px;
  line-height: 26px;
  border: 1px solid #d8dce5;
  color: #495060;
  background: #fff;
  padding: 0 8px;
  font-size: 12px;
  margin-left: 5px;
  margin-top: 4px;
}

/* 激活标签页样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: rgb(64, 158, 255) !important;
  /* 蓝色背景 */
  color: #fff !important;
  /* 白色文字 */
  border-color: rgb(64, 158, 255);
  /* 蓝色边框 */
  width: 110px;

  /* 添加白色小圆点 */
  &::before {
    content: '';
    /* 空内容 */
    display: inline-block;
    width: 6px;
    /* 圆点直径 */
    height: 6px;
    /* 圆点直径 */
    background-color: #fff;
    /* 白色 */
    border-radius: 50%;
    /* 圆形 */
    margin-right: 4px;
    /* 与文字间距 */
    vertical-align: middle;
    /* 垂直居中 */
  }
}

/* 移除默认激活边框 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  border-bottom-color: rgb(64, 158, 255);
}

/* 确保非激活状态下的标签页有默认样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  color: black;
  /* 默认黑色文字 */
}

.sidebar-logo-container .sidebar-logo[data-v-14eadf82] {
  width: 40px;
  margin-right: 0px;
}
.navbar {
  height: 50px;
  overflow: visible;
  /* 确保下拉菜单可以超出此元素 */
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-dropdown {
  margin-right: 16px;
  position: relative;
  /* 确保相对定位 */
  z-index: 1000;
  /* 提高z-index以确保下拉菜单可以在最上层 */
}

/* 增加下拉菜单的 z-index 并确保其不会受到任何父元素的影响 */
:deep(.el-dropdown-menu) {
  z-index: 1001 !important;
  /* 确保下拉菜单总是在最顶层 */
  position: absolute !important;
  /* 强制绝对定位 */
}

/* 防止其他全局样式影响 */
:deep(.el-popper) {
  z-index: 1001 !important;
  /* 确保 popper 容器也在最顶层 */
}

.el-dropdown-link img {
  vertical-align: middle;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.el-breadcrumb {
  margin-left: 30px;
  margin-top: 5px;
}

.el-main {
  margin-top: -36px;
}

/* 标签页的基本样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  display: inline-block;
  position: relative;
  cursor: pointer;
  height: 26px;
  line-height: 26px;
  border: 1px solid #d8dce5;
  color: #495060;
  background: #fff;
  padding: 0 8px;
  font-size: 12px;
  margin-left: 5px;
  margin-top: 4px;
}

/* 激活标签页样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  background-color: rgb(64, 158, 255) !important;
  /* 蓝色背景 */
  color: #fff !important;
  /* 白色文字 */
  border-color: rgb(64, 158, 255);
  /* 蓝色边框 */
  width: 110px;

  /* 添加白色小圆点 */
  &::before {
    content: '';
    /* 空内容 */
    display: inline-block;
    width: 6px;
    /* 圆点直径 */
    height: 6px;
    /* 圆点直径 */
    background-color: #fff;
    /* 白色 */
    border-radius: 50%;
    /* 圆形 */
    margin-right: 4px;
    /* 与文字间距 */
    vertical-align: middle;
    /* 垂直居中 */
  }
}

/* 移除默认激活边框 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item.is-active) {
  border-bottom-color: rgb(64, 158, 255);
}

/* 确保非激活状态下的标签页有默认样式 */
:deep(.el-tabs--card > .el-tabs__header .el-tabs__item) {
  color: black;
  /* 默认黑色文字 */
}

.sidebar-logo-container .sidebar-logo[data-v-14eadf82] {
  width: 40px;
  margin-right: 0px;
}

/* 父菜单标题样式 */
:deep(.el-sub-menu__title) {
  color: #fff !important;
  /* 字体颜色为白色 */
  background-color: rgb(48, 65, 86) !important;
  /* 默认背景颜色 */
  padding-left: 20px !important;
  /* 左侧内边距 */
  height: 50px;
  /* 高度 */
  line-height: 50px;
  /* 行高 */
  display: flex;
  align-items: center;
  /* 图标和文字垂直居中对齐 */

  /* 图标和文字间距 */
  // .el-icon {
  //   margin-right: 10px;
  // }
}

/* 父菜单标题鼠标悬停时的背景颜色 */
:deep(.el-sub-menu__title:hover) {
  background-color: #313e51 !important;
  /* 悬停时背景颜色 */
}

/* 子菜单项样式 */
:deep(.el-sub-menu .el-menu-item) {
  color: #fff !important;
  /* 字体颜色为白色 */
  background-color: rgb(48, 65, 86) !important;
  /* 背景颜色 */
  padding-left: 40px !important;
  /* 增加缩进，区分层级 */
  height: 50px;
  /* 高度 */
  line-height: 50px;
  /* 行高 */
}

/* 子菜单项鼠标悬停时的背景颜色 */
:deep(.el-sub-menu .el-menu-item:hover) {
  background-color: #313e51 !important;
  /* 悬停时背景颜色 */
}

/* 弹出层背景颜色 */
:deep(.el-menu--popup) {
  background-color: rgb(48, 65, 86) !important;
  /* 弹出层背景颜色 */
  border: none !important;
  /* 去掉边框 */
}

/* 弹出层中的子菜单项样式 */
:deep(.el-menu--popup .el-menu-item) {
  color: #fff !important;
  /* 字体颜色为白色 */
  background-color: rgb(48, 65, 86) !important;
  /* 背景颜色 */
  padding-left: 20px !important;
  /* 左侧内边距 */
  height: 50px;
  /* 高度 */
  line-height: 50px;
  /* 行高 */
}

/* 弹出层中的子菜单项鼠标悬停时的背景颜色 */
:deep(.el-menu--popup .el-menu-item:hover) {
  background-color: #313e51 !important;
  /* 悬停时背景颜色 */
}

/* 折叠模式下的样式 */
// .el-menu--collapse :deep(.el-sub-menu__title) {
//   padding-left: 10px !important; /* 折叠时的内边距 */
// }

.el-menu--collapse :deep(.el-sub-menu .el-menu-item) {
  padding-left: 20px !important;
  /* 折叠时子菜单项的内边距 */
}

/* 确保 <span> 在折叠状态下隐藏 */
.el-menu--collapse .el-menu-item span,
.el-menu--collapse .el-submenu__title span {
  display: none;
}

.user-dropdown {
  display: flex; /* 启用 flexbox 布局 */
  align-items: center; /* 垂直居中对齐 */
  // gap: 10px; /* 设置子元素之间的间距 */
}

.el-dropdown-link {
  display: flex; /* 确保下拉菜单内容水平排列 */
  align-items: center; /* 垂直居中对齐 */
}

.el-button {
  height: auto; /* 确保按钮高度与其他元素一致 */
  line-height: normal; /* 调整按钮文字的行高 */
}
</style>